import { getToken, removeToken, setToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 清除过期token
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, obj) {
    state.userInfo = obj
  }
}
const actions = {
  async login(ctx, { mobile, password }) {
    const res = await login({ mobile, password })
    console.log(res)
    ctx.commit('setToken', res)
  },
  async getUserInfo(ctx) {
    const res = await getUserInfo()
    ctx.commit('setUserInfo', res)
  },
  // 页面中一个actions调用了两mutation
  logout(ctx) {
    ctx.commit('removeToken')
    ctx.commit('setUserInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

